<template>
  <div>
    <!-- 搜索区域 -->
    <el-row>
      <el-form :inline="true" :model="queryInfo">
        <el-form-item label="名称">
          <el-input v-model="queryInfo.title" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getdata">搜索</el-button>
          <el-button type="primary" @click="showAddcommd">新增心理知识</el-button>
          <el-button type="danger" @click="delBacth">批量删除</el-button>
          <!-- 新增或修改弹出框 -->
          <el-dialog
            v-model="dialogVisible"
            :title="title"
            width="600"
            :before-close="cancel"
            ref:ruleFormRef
          >
            <el-form
              :model="dataList"
              label-width="auto"
              style="max-width: 600px"
              ref="ruleFormRef"
              :rules="rules"
            >
              <el-form-item label="活动标题">
                <el-input
                  v-model="dataList.title"
                  placeholder="请输入活动标题"
                  style="width: 500px;"
                />
              </el-form-item>
              <el-form-item label="简介">
                <el-input
                  v-model="dataList.description"
                  placeholder="请输入简介"
                  style="width: 500px;"
                />
              </el-form-item>
              <el-form-item label="活动详情">
                <QuillEditor v-model:content="dataList.content" 
                :options="editorOptions" 
                @update="handleQuillChange" contentType="html"/>
              </el-form-item>
              <el-form-item label="封面图">
                <el-upload
                  drag
                  class="avatar-uploader"
                  method="post"
                  action="http://localhost:8081/sfzy/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="form.imgUrl" :src="`${form.imgUrl}`" class="avatar" />
                  <div v-else>
                    <el-icon class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item id="button">
                <el-button type="primary" @click="add" v-if="dataList.addOrUpdateFlag<3">确认</el-button>
                <el-button type="primary" @click="cancel" v-if="dataList.addOrUpdateFlag<3">取消</el-button>
    
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表格区域 -->
    <el-table
      :data="dataList1"
      border
      style="width: 100%"
      stripe="true"
      :row-style="{height: '50px'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" label="ID"></el-table-column>
      <el-table-column align="center" prop="title" label="文章名称"></el-table-column>
      <el-table-column align="center" prop="description" label="文章简介"></el-table-column>
      <el-table-column prop="thumbnailUrl" label="封面图" width="130">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px; text-align: center"
            :src="'http://localhost:8081/sfzy' + scope.row.thumbnailUrl"
            fit="contain"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="consult.name" label="作者"></el-table-column> 
      <el-table-column align="center" label="操作">
        <template v-slot="scope">
          <el-button type="primary" plain @click="showUpdatecommd(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div id="footer">
      <el-pagination
        background
        :default-page-size="5"
        :page-sizes="[5, 8, 10]"
        :size="size"
        :disabled="disabled"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="changePageNum"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
    
<script setup >
import {
  ref,
  onMounted,
  getCurrentInstance,
  watchEffect,
  onBeforeUnmount,
  reactive,
  toRaw,
  watch,
  nextTick 
} from "vue";
import {
  ElMessageBox,
  ElMessage
} from "element-plus";

import { SortUp, Plus } from "@element-plus/icons-vue";
import ArticleCategory from "./ArticleCategory.vue";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

const dialogVisible = ref(false);
const ruleFormRef = ref();
const dialogRef = ref(null); // 对话框的ref
const currentInstance = getCurrentInstance();
const { $http } = currentInstance.appContext.config.globalProperties;
const daterange = ref("");
const dataList1 = ref([]);
const typeList = ref([]);
// 定义响应式数据content，初始为空字符串

const quillEditorRef = ref(null);

const total = ref();
const title = ref("");
const address = ref("");
let options = ref([]);
let ids = ref([]);

// 定义查询对象 用来获取表单数据
let queryInfo = ref({
  title: "",
  pageNum: 1,
  pageSize: 5
});
// 定义新增或修改信息对象
const dataList = ref({
  addOrUpdateFlag: 1, // 判断是新增还是修改的标志 1:新增 2：修改
  id: 0, // id
  title: "", // 名称
  description: "", // 简介
  consultantId: 2, // 咨询师id
  thumbnailUrl: "", // 缩略图地址
  content: "", // 详情
  

  del: 0 //逻辑删除状态
});

/*----------------封面图部分------------------------*/
let form = ref({
  imgUrl: ""
});
const imageUrl = ref(""); // 图片上传成功的钩子
const handleAvatarSuccess = (response, uploadFile) => {
  // 保存相对路径到相关数据对象，以便传给后端
  const relativeImagePath = response.data; // 拼接完整的图片路径在弹出框中显示
  const fullImagePath = `http://localhost:8081/sfzy${response.data}`;
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.value.imgUrl = fullImagePath; //传回数据库的路径
  dataList.value.thumbnailUrl = relativeImagePath;
};
onBeforeUnmount(() => {
  URL.revokeObjectURL(imageUrl.value);
});
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload = rawFile => {
  const allowedFormats = ["image/jpeg", "image/png"]; // 允许的文件格式
  if (!allowedFormats.includes(rawFile.type)) {
    this.$message.error("文件格式必须是 JPG 或 PNG！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
/*----------------富文本部分------------------------*/
// const props = defineProps(["value"]);
// const emit = defineEmits(["updateValue"]);
// const content = ref("");
// const myQuillEditor = ref();
// // 通过watch监听回显，这边使用v-model:content 不能正常回显
// watch(
//   () => props.value,
//   val => {
//     toRaw(myQuillEditor.value).setHTML(val);
//   },
//   { deep: true }
// );
// const fileBtn = ref();
// const data = reactive({
//   content: "",
//   editorOption: {
//     modules: {
//       toolbar: [
//         ["bold", "italic", "underline", "strike"],
//         [{ size: ["small", false, "large", "huge"] }],
//         [{ font: [] }],
//         [{ align: [] }],
//         [{ list: "ordered" }, { list: "bullet" }],
//         [{ indent: "-1" }, { indent: "+1" }],
//         [{ header: 1 }, { header: 2 }],
//         ["image"],
//         [{ direction: "rtl" }],
//         [{ color: [] }, { background: [] }]
//       ]
//     },
//     placeholder: "请输入内容..."
//   }
// });
// const imgHandler = state => {
//   if (state) {
//     fileBtn.value.click();
//   }
// };
// // 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
// const setValue = () => {
//   const text = toRaw(myQuillEditor.value).getHTML();
// };
// const handleUpload = e => {
//   const files = Array.prototype.slice.call(e.target.files);
//   // console.log(files, "files")
//   if (!files) {
//     return;
//   }
//   const formdata = new FormData();
//   formdata.append("file", files[0]);
//   backsite
//     .uploadFile(formdata) // 此处使用服务端提供上传接口
//     .then(res => {
//       if (res.data.url) {
//         const quill = toRaw(myQuillEditor.value).getQuill();
//         const length = quill.getSelection().index;
//         quill.insertEmbed(length, "image", res.data.url);
//         quill.setSelection(length + 1);
//       }
//     });
// };
// // 初始化编辑器
// // onMounted(() => {
 
// // });

/*----------------添加或修改数据------------------------*/
//添加或修改数据
function add() {
  if (dataList.value.addOrUpdateFlag == 1) {
    $http({
      method: "post",
      url: "http://localhost:8081/sfzy/psychologicalKnowledge",
      data: dataList.value
    }).then(res => {
      console.log("res=" + res);
      if (res.data.code == 200) {
        ElMessage.success("添加成功！");
        res.data.message;
      } else {
        ElMessage.error("添加失败！");
      }
      //再次查询
      getdata();
      //调用取消清空数据
      cancel();
    });
  } else if (dataList.value.addOrUpdateFlag == 2) {
    $http({
      method: "put",
      url: "http://localhost:8081/sfzy/psychologicalKnowledge",
      data: dataList.value
    }).then(res => {
      console.log("res=" + res);
      if (res.data.code == 200) {
        ElMessage.success("修改成功！");
        res.data.message;
      } else {
        ElMessage.error("修改失败！");
      }
      //再次查询
      getdata();
      //调用取消清空数据
      cancel();
    });
  }
}

//挂载后执行请求数据
onMounted(() => {
  getdata();
});
//数据请求方法
function getdata() {
  $http({
    method: "get",
    url: "http://localhost:8081/sfzy/psychologicalKnowledge/page",
    params: queryInfo.value
  }).then(res => {
    dataList1.value = res.data.data.list;
    total.value = res.data.data.total;
  });
}

//获取selection中的数据
function handleSelectionChange(val) {
  ids.value = val.map(item => item.id);
}


//pageNum
function changePageNum(num) {
  // 修改页码
  queryInfo.value.pageNum = num;
  //再次查询
  getdata();
}

//pageSize
function handleSizeChange(size) {
  queryInfo.value.pageSize = size;
  getdata();
}

//新增文章
function showAddcommd() {
  title.value = "新增文章";
  dialogVisible.value = true;
  dataList.value.addOrUpdateFlag = 1;
}

//修改文章
function showUpdatecommd(val) {
  console.log(val);
  title.value = "修改文章";
  dialogVisible.value = true;
  dataList.value.addOrUpdateFlag = 2;

  // 回显
  Object.assign(dataList.value, {
    id: val.id,
    title: val.title,
    description: val.description,
    consultantId: val.consultantId,
    thumbnailUrl: val.thumbnailUrl,
    content: val.content,
    del: val.del
  });

  form.value.imgUrl = `http://localhost:8081/sfzy${val.thumbnailUrl}`;
}

//取消
function cancel() {
  dialogVisible.value = false;
  address.value = [];
  form.value.imgUrl = "";
  Object.assign(dataList.value, {
    addOrUpdateFlag: 1,
    id: 0,
    title: "",
    description: "",
    consultantId: 2,
    thumbnailUrl: "",
    content: "",
    del: 0
  });
  //再次查询
  getdata();
}

/*---------------- 删除/批量删除 部分------------------------*/
//删除
function del(id) {
  ElMessageBox.confirm("确认要删除数据吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      $http({
        method: "delete",
        url: "http://localhost:8081/sfzy/psychologicalKnowledge/" + id
      }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功！");
          getdata();
        } else {
          ElMessage.error("删除失败！");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除！"
      });
    });
}
//批量删除
function delBacth() {
  if (ids.value != null && ids.value != "") {
    ElMessageBox.confirm("确认要删除数据吗?", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        $http({
          method: "delete",
          url: "http://localhost:8081/sfzy/psychologicalKnowledge?ids=" + ids.value
        }).then(res => {
          if (res.data.code == 200) {
            ElMessage.success("删除成功！");
            getdata();
          } else {
            ElMessage.error("删除失败！");
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！"
        });
      });
  }
}
</script>
    
<style scoped>
:deep(.ql-container) {
  min-height: 200px;
  min-width: 468px;
  max-width: 468px;
  max-height: 200px;
}

#button {
  margin-left: 250px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-pagination {
  margin-left: 200px;
}

#footer {
  height: 80px;
  margin: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
}
</style>